package cn.plem.handler;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import javax.ws.rs.Path;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

@Path("/csvml")
public class WhoamiHandler implements HttpHandler {

	/**
	 * http://localhost/cn.plem.handler.PingHandler
	 */
	public static void main(String[] args) throws IOException {
		new WhoamiHandler(args.length == 0 ? 80 : Integer.parseInt(args[0]));
	}

	public WhoamiHandler() {
	}

	public WhoamiHandler(int port) throws IOException {
		InetSocketAddress ip = new InetSocketAddress(port);
		HttpServer server = HttpServer.create(ip, 0);
		server.createContext("/csvml", this);
		server.setExecutor(Executors.newCachedThreadPool());
		server.start();
		System.out.println(String.format("httpserver startup on %s ...", port));
	}

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		exchange.sendResponseHeaders(200, 0);
		OutputStream out = exchange.getResponseBody();
		Headers requestHeaders = exchange.getRequestHeaders();
		requestHeaders.keySet().forEach(key -> {
			try {
				out.write(String.format("%s=%s\n", key, requestHeaders.get(key)).getBytes());
			} catch (IOException e) {
				System.out.print(e.getMessage());
			}
		});
		out.close();
	}

}
